<?php

namespace app\admin\controller\admin;

use support\Request;
use app\admin\controller\BaseController;
use app\admin\service\admin\DepartmentService;

class DepartmentController extends BaseController
{
    protected array $noNeedLogin = [];

    public function __construct(DepartmentService $service)
    {
        parent::__construct();
        $this->service = $service;
    }

    public function index(Request $request)
    {
        $do = $request->get('do');
        if ($request->isAjax() && $do == 'json') {
            $where = [];

            $result = $this->service->getDataList($where);

            if ($result['count'] == 0) {
                $data = [
                    'code' => -1,
                    'msg' => '未查询到数据'
                ];
            } else {
                $data = [
                    'code' => 0,
                    'msg' => '',
                    'count' => $result['count'],
                    'data' => $result['list']
                ];
            }
            return json($data);
        }

        return $this->fetch('admin/menu/index');
    }

    public function add(Request $request)
    {
        if ($request->isAjax()) {
            $data = $this->checkField(['pid|0', 'title', 'note|null', 'sort|0']);

            return $this->service->addDept($data);
        }
        return json(['code' => -1, 'msg' => '请求错误']);
    }

    public function edit(Request $request)
    {
        if ($request->isAjax()) {
            $data = $this->checkField(['id', 'pid|0', 'title', 'note|null', 'sort|0']);

            return $this->service->editDept($data);
        }
        return json(['code' => -1, 'msg' => '请求错误']);
    }

    public function del(Request $request)
    {
        if ($request->isAjax()) {
            $data = $this->checkField(['id']);
            return $this->service->delDept($data);
        }
        return json(['code' => -1, 'msg' => '请求错误']);
    }

}